package com.education.webservlet;

import com.education.util.Constant;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by Fan307 on 2016/11/24.
 * 参考代码：http://bbs.csdn.net/topics/10228613
 * 后期学习代码：http://blog.csdn.net/kuangfengbuyi/article/details/6998446
 */
@WebServlet(name = "MergeFolderServlet")
public class MergeFolderServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding(Constant.CHAR_ENCODING);
        File merged =  new File(request.getParameter("SelectFolder"));
        File mergeTo = new File(request.getParameter("MergeFolder"));
        try {
            boolean mergeSms = mergeDirByFile(merged, mergeTo);
            if(mergeSms == true)
            {
                PrintWriter out=response.getWriter();
                out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
                out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
                out.println("<HTML>");
                out.println("<HEAD><TITLE>Sucess</TITLE>");
                out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
                out.println("</HEAD>");
                out.println("<BODY>");
                out.println("<h2>Filse Moved Completely!</h2>");
                out.println("<br>");
                out.println("<input type=button value=\"Back\" onclick=\"window.history.go(-1)\">");
                out.println("</BODY>");
                out.println("</HEAD>");
                out.println("</HTML>");
                out.flush();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    public static boolean mergeDirByFile( File merged, File mergeTo ) throws Exception
    {
        if ( !merged.exists() ||!mergeTo.exists() )
            return false;
        if ( merged == null ||!merged.isDirectory() )
            throw new Exception( "想移动的文件对象为空或不是文件夹! " );
        if ( mergeTo == null ||!mergeTo.isDirectory() )
            throw new Exception( "目的文件对象为空或不是文件夹! " );
        File[] child = merged.listFiles();
        for ( int i = 0; i < child.length; i++ )
        {
            File destDir = new File( mergeTo.getAbsolutePath() + File.separator + child[ i ].getName() );
            if ( destDir.exists() && destDir.isFile() )
                destDir = new File( destDir.getAbsolutePath() + "-moved" );
            if ( child[ i ].isFile() )
                if ( !child[ i ].renameTo( destDir ) )
                    return false;
            if ( child[ i ].isDirectory() )
            {
                if ( !destDir.exists() )
                    if ( !( destDir.mkdir() ) )
                        return false;
                if ( !mergeDirByFile( child[ i ], destDir ) )
                    return false;
            }
        }
        return deleteDirByFile( merged );
    }

    public static boolean createFileByRelative( ServletContext application, String path, String fileName,
                                                String content ) throws Exception
    {
        return createFileByRelative( application, path, fileName, content.getBytes() );
    }

    public static boolean createFileByRelative(ServletContext application, String path, String fileName,
                                               byte[] b ) throws Exception
    {
        if ( !path.startsWith( "/" ) )
            path = "/" + path;
        String realPath = application.getRealPath( path );
        File file = new File( realPath );
        return createFileByFile( file, fileName, b );
    }

    public static boolean createFileByFile( File parent, String fileName, byte[] b ) throws Exception
    {
        if ( !parent.exists() )
            if ( !parent.mkdirs() )
                throw new Exception( "创建文件目录失败！" );
        fileName = parent.getAbsolutePath() + File.separator + fileName;
        File file = new File( fileName );
        FileOutputStream fos = new FileOutputStream( file );
        fos.write( b );
        fos.flush();
        fos.close();
        return true;
    }

    public static boolean deleteDirByFile( File file ) throws Exception
    {
        if ( !file.exists() )
            return false;
        if ( file == null ||!file.isDirectory() )
            throw new Exception( "文件对象为空或不是文件夹! " );
        File[] child = file.listFiles();
        for ( int i = 0; i < child.length; i++ )
        {
            if ( child[ i ].isFile() )
                if ( !( child[ i ].delete() ) )
                    return false;
            if ( child[ i ].isDirectory() )
                return deleteDirByFile( child[ i ] );
        }
        if ( !( file.delete() ) )
            return false;
        return true;
    }

}
